package com.moore.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.IService;
import com.moore.bean.Candidate;
import com.moore.dto.ResponseData;
import com.moore.mapper.LoginMapper;
import com.moore.service.LoginService;
import com.moore.utils.JwtUtil;
import jakarta.servlet.http.HttpServletRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.concurrent.TimeUnit;
import java.util.logging.Logger;

@Service
public class LoginServiceImpl implements LoginService {

    private static final Logger logger = Logger.getLogger(LoginServiceImpl.class.getName());

    @Autowired
    private LoginMapper loginMapper;

    @Autowired
    private RedisTemplate<String,String> redisTemplate;

    @Override
    public ResponseData LoginByPwd(String account, String password, HttpServletRequest request) {
        Candidate candidate = loginMapper.LoginByPwd(account, password);
        if (candidate != null) {
            String uuid = request.getHeader("UUID");
            return getResponseData(candidate, uuid);
        } else {
            return ResponseData.error("账号密码不正确");
        }
    }

    @Override
    public ResponseData LoginByCode(String account, String code, HttpServletRequest request) {
        QueryWrapper<Candidate> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("account", account);
        Candidate candidate = loginMapper.selectOne(queryWrapper);
        if (candidate == null) {
            return ResponseData.error("账号不存在");
        }
        String uuid = request.getHeader("UUID");
        if (uuid == null || uuid.isEmpty()) {
            return ResponseData.error("UUID不能为空");
        }
        String storedCode = redisTemplate.opsForValue().get(uuid);
        if (storedCode == null) {
            return ResponseData.error("验证码已过期或不存在");
        }
        if (!code.equals(storedCode)) {
            return ResponseData.error("验证码不正确");
        }
        return getResponseData(candidate, uuid);
    }

    private ResponseData getResponseData(Candidate candidate, String uuid) {
        String token = JwtUtil.generateToken(String.valueOf(candidate.getCandidateId()));
        try {
            redisTemplate.opsForValue().set("token:" + uuid, token, 30, TimeUnit.MINUTES);
        } catch (Exception e) {
            logger.severe("Failed to set token in Redis: " + e.getMessage());
            return ResponseData.error("Internal server error");
        }
        candidate.setToken(token);
        return ResponseData.returnObject("登录成功",candidate);
    }
}
